<?php

class SessionSaveHandlerMemcache implements SessionSaveHandler {
	static $maxLifeTime = 1440;
	static $compress = FALSE;
	private $handler;
	function __construct($settings,$options){
		if(!class_exists('Memcache') || !function_exists('memcache_connect')){
			trigger_error('Memcache Session Init failed Class Not Exist.', E_USER_ERROR);
			return false;
		}
		if(empty($settings) || empty($settings['memcache']['servers'])){
			trigger_error('Memcache Session Init failed Settings Empty.', E_USER_ERROR);
			return false;
		}
		is_array($options) && isset($options['gc_maxlifetime']) && self::$maxLifeTime = $options['gc_maxlifetime'];
		isset($settings['memcache']['compress']) && self::$compress = $settings['memcache']['compress'];
		$this->handler = new Memcache;
		foreach($settings['memcache']['servers'] as $server){
			$this->handler->addServer($server['host'],$server['port']);
		}
	}
    function open($save_path, $session_name){
        return true;
    }

    function close(){
        return true;
    }

    function read($session_id){
		return $this->handler->get("sess_{$session_id}");
    }

    function write($session_id, $session_data){
		return $this->handler->set("sess_{$session_id}",$session_data,self::$compress,self::$maxLifeTime);
    }

    function destroy($session_id){
		return $this->handler->delete("sess_{$session_id}"); // memcache缓存
    }

    function gc($maxlifetime=0){
       return true;
    }
}
?>